import java.util.LinkedList;
import java.util.Queue;

/**
 * @author LKQ
 * @date 2021/12/7 15:42
 * @description 迭代，广度优先搜索。每次将一层的所有节点加入队列，然后
 */
public class Solution2 {
    public static void main(String[] args) {
        TreeNode leaf9 = new TreeNode(9, null, null);
        TreeNode leaf15 = new TreeNode(15, null, null);
        TreeNode leaf7 = new TreeNode(7, null, null);
        TreeNode leaf20 = new TreeNode(20, leaf15, leaf7);
        TreeNode root = new TreeNode(3, leaf9, leaf20);
        Solution2 solution = new Solution2();
        System.out.println(solution.maxDepth(root));
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }
}
